const { Controller } = require('egg');
const fs = require('fs');
const moment = require('moment');
const mkdirp = require('mkdirp');
const path = require('path');
const api = require('../utils/utils').api;
const xlsx = require('xlsx')
const Response = require('../utils/Response')
// let api = "http://43.142.185.98:7001/"

/**
 * @Controller  文件图片上传相关模块
 */
class UploadController extends Controller {
  /**
  * @Router post /imgUpload
  * @Summary 图片上传
  * @Description 用于进行图片上传
  * @Request formData file *file
  */
  async imgUpload() {
    // let {ctx,service} = this
    // const path = require('path')
    // const fs = require('fs')
    // let file = ctx.request.files[0]
    // console.log(file);
    const { ctx } = this;
    // 需要前往 config/config.default.js 设置 config.multipart 的 mode 属性为 file
    const file = ctx.request.files[0];
    // 声明存放资源的路径
    let uploadDir = '';
    let id = '';
    try {
      // ctx.request.files[0] 表示获取第一个文件，若前端上传多个文件则可以遍历这个数组对象
      const f = fs.readFileSync(file.filepath);
      // 1.获取当前日期
      const day = moment(new Date()).format('YYYYMMDD');
      // 2.创建图片保存的路径
      const dir = path.join(this.config.uploadDir, day);
      const date = Date.now(); // 毫秒数
      await mkdirp(dir); // 不存在就创建目录
      // 返回图片保存的路径
      uploadDir = path.join(dir, date + path.extname(file.filename));
      //  反斜杠转斜杠
      uploadDir = uploadDir.replace(/\\/g, "/")
      // decodeURI是为了中文乱码
      //   id = await ctx.service.upload.add({ img_url: api + uploadDir, filename: decodeURI(file.filename) });
      //   console.log(id);
      // 写入文件夹
      fs.writeFileSync(uploadDir, f);
      let lastUrl = api + uploadDir
      ctx.body = new Response(200, lastUrl, "操作成功")
    } catch (e) {
      // console.log('error', e);
      // 清除临时文件
      ctx.cleanupRequestFiles();

    }

  }

  // excel导入 mysql
  /**
* @Router post /ExcelUpload
* @Summary Excel上传到数据库中
* @Description 用于进行将excel文件解析上传到数据库中
* @Request formData file *file
* @Request formData number *roleId
*/
  async ExcelUpload() {
    const { ctx, service } = this;
    // this.uploadFileStream()
    let { roleId } = ctx.request.body
    roleId = parseInt(roleId)

    const file = ctx.request.files[0];
    const list = new Array(0);

    const workbook = xlsx.readFile(file.filepath);
    for (const sheet in workbook.Sheets) {
      if (workbook.Sheets.hasOwnProperty(sheet)) {
        // 数据直接转成json格式 
        list.push(xlsx.utils.sheet_to_json(workbook.Sheets[sheet]));
      }
    }

    let trueList = list[0]
    let res = await service.upload.ExcelUpload(trueList, roleId)
    ctx.body = new Response(200, "上传完毕", "")


  }



}

module.exports = UploadController;